#!/bin/bash

# IoT设备开发框架统一管理脚本
# 功能：环境搭建、编译、清理、部署等统一管理

set -e  # 遇到错误立即退出

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="$PROJECT_ROOT/build"
OUTPUT_DIR="$PROJECT_ROOT/out"
TCU_BUILD_DIR="$BUILD_DIR/tcu"
TCU_OUTPUT_DIR="$OUTPUT_DIR/tcu"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo -e "${PURPLE}================================${NC}"
    echo -e "${PURPLE} $1${NC}"
    echo -e "${PURPLE}================================${NC}"
}

print_step() {
    echo -e "${CYAN}[STEP]${NC} $1"
}

# 显示帮助信息
show_help() {
    cat << EOF
IoT设备开发框架统一管理脚本 v1.0.0

用法: $0 [命令] [选项]

主要命令:
  setup          设置开发环境
  build          编译项目
  clean          清理构建文件
  deploy         部署到输出目录
  run            运行TCU应用
  test           运行测试
  package        打包发布

环境配置命令:
  env            配置开发环境（支持交叉编译）
  env-clean      清理环境配置
  fetch-deps     拉取第三方库
  clean-deps     清理第三方库
  fetch-mqtt     拉取MQTT SDK
  clean-mqtt     清理MQTT SDK

项目命令:
  create         创建新项目
  list           列出所有项目
  build-project  构建指定项目
  run-project    运行指定项目

选项:
  -a, --arch ARCH        目标架构 (x86_64|arm64|arm|riscv|native)
  -c, --cross            启用交叉编译
  -v, --verbose          详细输出
  -q, --quiet            静默模式
  -f, --force            强制操作

高级选项:
  --toolchain TOOL       工具链 (gcc|clang)
  --sysroot PATH         系统根目录
  --toolchain-prefix PREFIX 编译器前缀
  --toolchain-path PATH  工具链安装路径

示例:
  # 基本使用
  $0 setup        # 设置开发环境
  $0 build        # 编译项目
  $0 deploy       # 部署到输出目录
  $0 run          # 运行TCU应用

  # 环境配置
  $0 env -a native                    # 配置本地编译环境
  $0 env -a arm64 -c                  # 配置ARM64交叉编译环境
  $0 env -a arm -c --toolchain-path /opt/gcc-arm  # 使用自定义工具链
  $0 fetch-deps                       # 拉取第三方库
  $0 clean-deps                       # 清理第三方库
  $0 fetch-mqtt                       # 拉取MQTT SDK
  $0 clean-mqtt                       # 清理MQTT SDK

  # 项目管理
  $0 create myapp                     # 创建新项目
  $0 list                            # 列出所有项目
  $0 build-project myapp             # 构建指定项目

  # 完整流程
  $0 env -a native && $0 build && $0 deploy && $0 test

EOF
}

# 检查依赖
check_dependencies() {
    print_info "检查系统依赖..."
    
    local missing_deps=()
    
    # 检查基本工具
    command -v gcc >/dev/null 2>&1 || missing_deps+=("gcc")
    command -v make >/dev/null 2>&1 || missing_deps+=("make")
    command -v cmake >/dev/null 2>&1 || missing_deps+=("cmake")
    command -v pkg-config >/dev/null 2>&1 || missing_deps+=("pkg-config")
    command -v git >/dev/null 2>&1 || missing_deps+=("git")
    
    # 检查开发库
    pkg-config --exists openssl || missing_deps+=("libssl-dev")
    pkg-config --exists libcrypto || missing_deps+=("libssl-dev")
    
    if [ ${#missing_deps[@]} -ne 0 ]; then
        print_error "缺少以下依赖:"
        for dep in "${missing_deps[@]}"; do
            echo "  - $dep"
        done
        echo ""
        echo "安装命令:"
        echo "  sudo apt update"
        echo "  sudo apt install ${missing_deps[*]}"
        return 1
    fi
    
    print_success "所有依赖检查通过"
    return 0
}

# 拉取第三方库
fetch_third_party_libs() {
    print_info "拉取第三方库..."
    
    local third_party_dir="$PROJECT_ROOT/third_party"
    mkdir -p "$third_party_dir"
    
    # 第三方库配置
    local libs=(
        "cJSON|https://github.com/DaveGamble/cJSON.git|master"
    )
    
    for lib_info in "${libs[@]}"; do
        IFS='|' read -r lib_name lib_url lib_branch <<< "$lib_info"
        local lib_dir="$third_party_dir/$lib_name"
        
        if [ -d "$lib_dir" ]; then
            print_info "第三方库 $lib_name 已存在，跳过拉取"
            continue
        fi
        
        print_info "拉取 $lib_name..."
        if git clone -b "$lib_branch" "$lib_url" "$lib_dir"; then
            print_success "成功拉取 $lib_name"
        else
            print_error "拉取 $lib_name 失败，请检查网络连接和仓库地址"
            return 1
        fi
    done
    
    print_success "第三方库拉取完成"
    return 0
}

# 拉取MQTT SDK
fetch_mqtt_sdk() {
    print_info "拉取MQTT SDK..."
    
    local mqtt_dir="$PROJECT_ROOT/mqtt"
    mkdir -p "$mqtt_dir"
    
    # MQTT SDK配置
    local sdk_repos=(
        "paho.mqtt.c|https://github.com/eclipse/paho.mqtt.c.git|master"
    )
    
    for repo_info in "${sdk_repos[@]}"; do
        IFS='|' read -r repo_name repo_url repo_branch <<< "$repo_info"
        local repo_dir="$mqtt_dir/$repo_name"
        
        if [ -d "$repo_dir" ]; then
            print_info "MQTT SDK $repo_name 已存在，跳过拉取"
            continue
        fi
        
        print_info "拉取 $repo_name..."
        if git clone -b "$repo_branch" "$repo_url" "$repo_dir"; then
            print_success "成功拉取 $repo_name"
        else
            print_error "拉取 $repo_name 失败，请检查网络连接和仓库地址"
            return 1
        fi
    done
    
    print_success "MQTT SDK拉取完成"
    return 0
}

# 设置开发环境
setup_environment() {
    print_info "设置开发环境..."
    
    # 检查依赖
    if ! check_dependencies; then
        return 1
    fi
    
    # 拉取第三方库
    if ! fetch_third_party_libs; then
        return 1
    fi
    
    # 拉取MQTT SDK
    if ! fetch_mqtt_sdk; then
        return 1
    fi
    
    # 创建必要目录
    mkdir -p "$BUILD_DIR"
    mkdir -p "$OUTPUT_DIR"
    mkdir -p "$TCU_BUILD_DIR"
    mkdir -p "$TCU_OUTPUT_DIR"
    
    # 检查日志系统
    if [ ! -d "$PROJECT_ROOT/log" ]; then
        print_error "日志系统不存在"
        return 1
    fi
    
    print_success "开发环境设置完成"
    return 0
}

# 配置开发环境（支持交叉编译）
configure_environment() {
    local target_arch="native"
    local cross_compile=false
    local toolchain="gcc"
    local sysroot=""
    local toolchain_prefix=""
    local toolchain_path=""
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -a|--arch)
                target_arch="$2"
                shift 2
                ;;
            -c|--cross)
                cross_compile=true
                shift
                ;;
            --toolchain)
                toolchain="$2"
                shift 2
                ;;
            --sysroot)
                sysroot="$2"
                shift 2
                ;;
            --toolchain-prefix)
                toolchain_prefix="$2"
                shift 2
                ;;
            --toolchain-path)
                toolchain_path="$2"
                shift 2
                ;;
            *)
                shift
                ;;
        esac
    done
    
    print_step "配置开发环境..."
    print_info "目标架构: $target_arch"
    print_info "交叉编译: $cross_compile"
    
    # 验证目标架构
    case "$target_arch" in
        x86_64|arm64|arm|riscv|native)
            ;;
        *)
            print_error "不支持的目标架构: $target_arch"
            print_info "支持的架构: x86_64, arm64, arm, riscv, native"
            return 1
            ;;
    esac
    
    # 创建环境配置文件
    create_environment_config "$target_arch" "$cross_compile" "$toolchain" "$sysroot" "$toolchain_prefix" "$toolchain_path"
    
    print_success "开发环境配置完成"
}

# 创建环境配置文件
create_environment_config() {
    local target_arch="$1"
    local cross_compile="$2"
    local toolchain="$3"
    local sysroot="$4"
    local toolchain_prefix="$5"
    local toolchain_path="$6"
    
    local config_file="$PROJECT_ROOT/config/environment.sh"
    
    # 如果没有指定前缀，根据架构自动设置默认前缀
    if [[ -z "$toolchain_prefix" && "$cross_compile" == true ]]; then
        case "$target_arch" in
            arm64)
                toolchain_prefix="aarch64-linux-gnu-"
                ;;
            arm)
                toolchain_prefix="arm-linux-gnueabihf-"
                ;;
            riscv)
                toolchain_prefix="riscv64-linux-gnu-"
                ;;
            x86_64)
                toolchain_prefix="x86_64-linux-gnu-"
                ;;
        esac
        print_info "自动设置编译器前缀: $toolchain_prefix"
    fi
    
    cat > "$config_file" << EOF
#!/bin/bash
# TCU项目环境配置文件
# 生成时间: $(date)

# 基本配置
TARGET_ARCH="$target_arch"
CROSS_COMPILE=$cross_compile
TOOLCHAIN="$toolchain"
TOOLCHAIN_PREFIX="$toolchain_prefix"
TOOLCHAIN_PATH="$toolchain_path"
SYSROOT="$sysroot"

# 编译器配置
# 默认使用本地编译器
export CC=gcc
export CXX=g++
export AR=ar
export AS=as
export LD=ld
export NM=nm
export OBJCOPY=objcopy
export OBJDUMP=objdump
export RANLIB=ranlib
export READELF=readelf
export STRIP=strip

# 如果启用交叉编译，则使用交叉编译工具链
if [[ "\$CROSS_COMPILE" == true ]]; then
    # 如果指定了工具链路径，添加到PATH
    if [[ -n "\$TOOLCHAIN_PATH" ]]; then
        export PATH="\$TOOLCHAIN_PATH/bin:\$PATH"
    fi
    
    # 设置交叉编译工具链
    if [[ -n "\$TOOLCHAIN_PREFIX" ]]; then
        export CC="\${TOOLCHAIN_PREFIX}gcc"
        export CXX="\${TOOLCHAIN_PREFIX}g++"
        export AR="\${TOOLCHAIN_PREFIX}ar"
        export AS="\${TOOLCHAIN_PREFIX}as"
        export LD="\${TOOLCHAIN_PREFIX}ld"
        export NM="\${TOOLCHAIN_PREFIX}nm"
        export OBJCOPY="\${TOOLCHAIN_PREFIX}objcopy"
        export OBJDUMP="\${TOOLCHAIN_PREFIX}objdump"
        export RANLIB="\${TOOLCHAIN_PREFIX}ranlib"
        export READELF="\${TOOLCHAIN_PREFIX}readelf"
        export STRIP="\${TOOLCHAIN_PREFIX}strip"
    fi
    
    # 设置目标三元组
    export TARGET_TRIPLET="\${TOOLCHAIN_PREFIX%-}"
    
    # 设置系统根目录
    if [[ -n "\$SYSROOT" ]]; then
        export SYSROOT="\$SYSROOT"
        export PKG_CONFIG_SYSROOT_DIR="\$SYSROOT"
        export PKG_CONFIG_LIBDIR="\$SYSROOT/usr/lib/pkgconfig:\$SYSROOT/usr/share/pkgconfig"
    fi
fi

# 编译选项
export CFLAGS="-Wall -Wextra -std=c99 -O2 -D_GNU_SOURCE"
export CXXFLAGS="-Wall -Wextra -std=c++11 -O2"

# 交叉编译特定选项
if [[ "\$CROSS_COMPILE" == true ]]; then
    case "\$TARGET_ARCH" in
        arm64)
            export CFLAGS="\$CFLAGS -march=armv8-a -mtune=cortex-a72"
            export CXXFLAGS="\$CXXFLAGS -march=armv8-a -mtune=cortex-a72"
            ;;
        arm)
            export CFLAGS="\$CFLAGS -march=armv7-a -mfpu=neon -mfloat-abi=hard"
            export CXXFLAGS="\$CXXFLAGS -march=armv7-a -mfpu=neon -mfloat-abi=hard"
            ;;
        riscv)
            export CFLAGS="\$CFLAGS -march=rv64gc -mabi=lp64d"
            export CXXFLAGS="\$CXXFLAGS -march=rv64gc -mabi=lp64d"
            ;;
        x86_64)
            export CFLAGS="\$CFLAGS -march=x86-64 -mtune=generic"
            export CXXFLAGS="\$CXXFLAGS -march=x86-64 -mtune=generic"
            ;;
    esac
    
    # 链接选项
    export LDFLAGS="-Wl,--hash-style=gnu"
fi

echo "环境已配置:"
echo "  编译模式: \$([ "\$CROSS_COMPILE" == true ] && echo "交叉编译" || echo "本地编译")"
echo "  目标架构: \$TARGET_ARCH"
echo "  CC: \$CC"
echo "  CXX: \$CXX"
echo "  CFLAGS: \$CFLAGS"
EOF

    chmod +x "$config_file"
    print_success "环境配置文件已创建: $config_file"
}

# 编译项目
build_project() {
    print_info "编译TCU项目..."
    
    # 确保环境已设置
    if [ ! -d "$TCU_BUILD_DIR" ]; then
        print_info "环境未设置，正在设置..."
        setup_environment
    fi
    
    # 加载环境配置
    if [ -f "$PROJECT_ROOT/config/environment.sh" ]; then
        source "$PROJECT_ROOT/config/environment.sh"
    fi
    
    # 进入TCU目录
    cd "$PROJECT_ROOT/app/tcu"
    
    # 编译
    if make clean && make; then
        print_success "编译完成"
        return 0
    else
        print_error "编译失败"
        return 1
    fi
}

# 清理构建文件
clean_project() {
    print_info "清理构建文件..."
    
    # 清理构建目录
    if [ -d "$BUILD_DIR" ]; then
        rm -rf "$BUILD_DIR"
        print_success "构建目录已清理: $BUILD_DIR"
    fi
    
    # 清理输出目录
    if [ -d "$OUTPUT_DIR" ]; then
        rm -rf "$OUTPUT_DIR"
        print_success "输出目录已清理: $OUTPUT_DIR"
    fi
    
    # 清理TCU目录中的构建文件
    if [ -d "$PROJECT_ROOT/app/tcu/build" ]; then
        rm -rf "$PROJECT_ROOT/app/tcu/build"
        print_success "TCU构建文件已清理"
    fi
    
    print_success "清理完成"
    return 0
}

# 清理环境配置
clean_environment() {
    print_info "清理环境配置..."
    
    if [ -f "$PROJECT_ROOT/config/environment.sh" ]; then
        rm -f "$PROJECT_ROOT/config/environment.sh"
        print_success "环境配置文件已清理"
    fi
    
    print_success "环境配置清理完成"
}

# 清理第三方库
clean_third_party_libs() {
    print_info "清理第三方库..."
    
    local third_party_dir="$PROJECT_ROOT/third_party"
    
    if [ -d "$third_party_dir" ]; then
        rm -rf "$third_party_dir"
        print_success "第三方库已清理: $third_party_dir"
    else
        print_info "第三方库目录不存在，无需清理"
    fi
    
    print_success "第三方库清理完成"
}

# 清理MQTT SDK
clean_mqtt_sdk() {
    print_info "清理MQTT SDK..."
    
    local mqtt_dir="$PROJECT_ROOT/mqtt"
    
    if [ -d "$mqtt_dir" ]; then
        rm -rf "$mqtt_dir"
        print_success "MQTT SDK已清理: $mqtt_dir"
    else
        print_info "MQTT SDK目录不存在，无需清理"
    fi
    
    print_success "MQTT SDK清理完成"
}

# 部署到输出目录
deploy_project() {
    print_info "部署项目到输出目录..."
    
    # 确保已编译
    if [ ! -f "$TCU_OUTPUT_DIR/tcu" ]; then
        print_info "项目未编译，正在编译..."
        build_project
    fi
    
    # 创建输出目录结构
    mkdir -p "$TCU_OUTPUT_DIR/config"
    mkdir -p "$TCU_OUTPUT_DIR/logs"
    mkdir -p "$TCU_OUTPUT_DIR/lib"
    
    # 复制配置文件
    if [ -d "$PROJECT_ROOT/app/tcu/config" ]; then
        cp -r "$PROJECT_ROOT/app/tcu/config"/* "$TCU_OUTPUT_DIR/config/"
        print_success "配置文件已复制"
    fi
    
    # 创建启动脚本
    cat > "$TCU_OUTPUT_DIR/start.sh" << 'EOF'
#!/bin/bash

# TCU应用启动脚本
# 自动设置环境并启动TCU应用

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 设置环境变量
export LD_LIBRARY_PATH="$SCRIPT_DIR/lib:$LD_LIBRARY_PATH"

# 检查可执行文件
if [ ! -f "./tcu" ]; then
    echo "错误: 找不到tcu可执行文件"
    exit 1
fi

# 检查配置文件
if [ ! -d "./config" ]; then
    echo "错误: 找不到config配置目录"
    exit 1
fi

# 创建日志目录
mkdir -p logs

# 启动TCU应用
echo "启动TCU应用..."
echo "工作目录: $SCRIPT_DIR"
echo "配置文件: $SCRIPT_DIR/config"
echo "日志目录: $SCRIPT_DIR/logs"
echo ""

exec ./tcu "$@"
EOF
    
    chmod +x "$TCU_OUTPUT_DIR/start.sh"
    print_success "启动脚本已创建"
    
    # 创建停止脚本
    cat > "$TCU_OUTPUT_DIR/stop.sh" << 'EOF'
#!/bin/bash

# TCU应用停止脚本

echo "正在停止TCU应用..."

# 查找TCU进程
TCU_PID=$(pgrep -f "tcu")
if [ -n "$TCU_PID" ]; then
    echo "找到TCU进程 PID: $TCU_PID"
    kill -TERM "$TCU_PID"
    
    # 等待进程结束
    for i in {1..10}; do
        if ! kill -0 "$TCU_PID" 2>/dev/null; then
            echo "TCU应用已停止"
            exit 0
        fi
        sleep 1
    done
    
    # 强制杀死进程
    echo "强制停止TCU应用..."
    kill -KILL "$TCU_PID" 2>/dev/null
    echo "TCU应用已强制停止"
else
    echo "未找到运行中的TCU应用"
fi
EOF
    
    chmod +x "$TCU_OUTPUT_DIR/stop.sh"
    print_success "停止脚本已创建"
    
    # 创建README文件
    cat > "$TCU_OUTPUT_DIR/README.md" << EOF
# TCU应用部署包

## 快速使用

### 启动应用
\`\`\`bash
./start.sh
\`\`\`

### 停止应用
\`\`\`bash
./stop.sh
\`\`\`

### 直接运行
\`\`\`bash
./tcu [选项]
\`\`\`

## 文件说明

- \`tcu\` - TCU应用主程序
- \`start.sh\` - 启动脚本
- \`stop.sh\` - 停止脚本
- \`config/\` - 配置文件目录
- \`logs/\` - 日志文件目录

## 命令行选项

- \`-c, --config <dir>\` - 指定配置目录
- \`-d, --daemon\` - 守护进程模式
- \`-l, --log-level <level>\` - 设置日志级别
- \`-h, --help\` - 显示帮助
- \`-v, --version\` - 显示版本

## 详细文档

更多详细信息请参考项目文档：
- 使用指南: ../../docs/使用指南.md
- 功能说明: ../../docs/功能说明.md

生成时间: $(date)
版本: 1.0.0
EOF
    
    print_success "README文件已创建"
    
    # 显示部署信息
    print_success "部署完成"
    echo ""
    echo "部署目录: $TCU_OUTPUT_DIR"
    echo "文件列表:"
    ls -la "$TCU_OUTPUT_DIR"
    echo ""
    echo "使用方法:"
    echo "  cd $TCU_OUTPUT_DIR"
    echo "  ./start.sh"
    
    return 0
}

# 运行TCU应用
run_application() {
    print_info "运行TCU应用..."
    
    # 确保已部署
    if [ ! -f "$TCU_OUTPUT_DIR/tcu" ]; then
        print_info "应用未部署，正在部署..."
        deploy_project
    fi
    
    # 进入输出目录并运行
    cd "$TCU_OUTPUT_DIR"
    exec ./start.sh "$@"
}

# 运行测试
run_tests() {
    print_info "运行测试..."
    
    # 确保已编译
    if [ ! -f "$TCU_OUTPUT_DIR/tcu" ]; then
        print_info "项目未编译，正在编译..."
        build_project
    fi
    
    # 运行基本测试
    cd "$TCU_OUTPUT_DIR"
    
    print_info "测试1: 版本信息"
    if ./tcu --version; then
        print_success "版本信息测试通过"
    else
        print_error "版本信息测试失败"
        return 1
    fi
    
    print_info "测试2: 帮助信息"
    if ./tcu --help >/dev/null; then
        print_success "帮助信息测试通过"
    else
        print_error "帮助信息测试失败"
        return 1
    fi
    
    print_success "所有测试通过"
    return 0
}

# 打包发布
package_release() {
    print_info "打包发布..."
    
    # 确保已部署
    if [ ! -f "$TCU_OUTPUT_DIR/tcu" ]; then
        print_info "项目未部署，正在部署..."
        deploy_project
    fi
    
    # 创建发布包
    local package_name="tcu-$(date +%Y%m%d-%H%M%S).tar.gz"
    local package_path="$PROJECT_ROOT/$package_name"
    
    cd "$PROJECT_ROOT"
    tar -czf "$package_path" -C "$OUTPUT_DIR" tcu
    
    print_success "发布包已创建: $package_path"
    echo "文件大小: $(du -h "$package_path" | cut -f1)"
    echo ""
    echo "部署到目标设备:"
    echo "  scp $package_path user@target:/tmp/"
    echo "  ssh user@target 'cd /opt && tar -xzf /tmp/$package_name'"
    
    return 0
}

# 创建新项目
create_project() {
    local project_name="$1"
    
    if [[ -z "$project_name" ]]; then
        print_error "请指定项目名称"
        return 1
    fi
    
    print_step "创建新项目: $project_name"
    
    local project_dir="$PROJECT_ROOT/app/$project_name"
    
    if [[ -d "$project_dir" ]]; then
        print_error "项目已存在: $project_dir"
        return 1
    fi
    
    mkdir -p "$project_dir/src" "$project_dir/include" "$project_dir/config"
    
    # 创建基本文件
    cat > "$project_dir/Makefile" << EOF
# $project_name Makefile
PROJECT_NAME = $project_name
SRC_DIR = src
INCLUDE_DIR = include
BUILD_DIR = ../../build/$project_name
OUTPUT_DIR = ../../out/$project_name

CC = gcc
CFLAGS = -Wall -Wextra -O2 -std=c99 -g -D_GNU_SOURCE
INCLUDES = -I\$(INCLUDE_DIR) -I../../log -I../../third_party/cJSON
LDFLAGS = -lpthread -lm -lssl -lcrypto

SOURCES = \$(wildcard \$(SRC_DIR)/*.c) ../../log/logger.c ../../third_party/cJSON/cJSON.c
OBJECTS = \$(SOURCES:%.c=\$(BUILD_DIR)/%.o)
TARGET = \$(OUTPUT_DIR)/\$(PROJECT_NAME)

all: \$(TARGET)

\$(TARGET): \$(OBJECTS) | \$(BUILD_DIR) \$(OUTPUT_DIR)
	@echo "链接 \$(PROJECT_NAME)..."
	\$(CC) \$(OBJECTS) -o \$@ \$(LDFLAGS)

\$(BUILD_DIR)/%.o: %.c | \$(BUILD_DIR)
	@echo "编译 \$<..."
	@mkdir -p \$(dir \$@)
	\$(CC) \$(CFLAGS) \$(INCLUDES) -c \$< -o \$@

\$(BUILD_DIR):
	@mkdir -p \$(BUILD_DIR)

\$(OUTPUT_DIR):
	@mkdir -p \$(OUTPUT_DIR)

clean:
	rm -rf \$(BUILD_DIR)

.PHONY: all clean
EOF

    cat > "$project_dir/src/main.c" << EOF
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
    printf("Hello from $project_name!\\n");
    return 0;
}
EOF

    print_success "项目创建完成: $project_dir"
}

# 列出所有项目
list_projects() {
    print_step "列出所有项目..."
    
    local app_dir="$PROJECT_ROOT/app"
    if [[ -d "$app_dir" ]]; then
        local projects=$(find "$app_dir" -maxdepth 1 -type d -not -path "$app_dir" | sed "s|$app_dir/||")
        if [[ -n "$projects" ]]; then
            echo "项目列表:"
            echo "$projects" | sed 's/^/  /'
        else
            echo "暂无项目"
        fi
    else
        echo "项目目录不存在"
    fi
}

# 构建指定项目
build_specific_project() {
    local project_name="$1"
    
    if [[ -z "$project_name" ]]; then
        print_error "请指定项目名称"
        return 1
    fi
    
    print_step "构建项目: $project_name"
    
    local project_dir="$PROJECT_ROOT/app/$project_name"
    
    if [[ ! -d "$project_dir" ]]; then
        print_error "未找到项目: $project_name"
        return 1
    fi
    
    cd "$project_dir"
    
    if [[ -f "Makefile" ]]; then
        make
        print_success "项目构建完成: $project_name"
    else
        print_error "未找到Makefile"
        return 1
    fi
}

# 运行指定项目
run_specific_project() {
    local project_name="$1"
    
    if [[ -z "$project_name" ]]; then
        print_error "请指定项目名称"
        return 1
    fi
    
    print_step "运行项目: $project_name"
    
    local project_dir="$PROJECT_ROOT/app/$project_name"
    local output_dir="$PROJECT_ROOT/out/$project_name"
    
    if [[ ! -d "$project_dir" ]]; then
        print_error "未找到项目: $project_name"
        return 1
    fi
    
    if [[ ! -f "$output_dir/$project_name" ]]; then
        print_info "项目未构建，正在构建..."
        build_specific_project "$project_name"
    fi
    
    cd "$output_dir"
    exec "./$project_name" "$@"
}

# 主函数
main() {
    local command="${1:-help}"
    shift || true
    
    case "$command" in
        setup)
            setup_environment
            ;;
        build)
            build_project
            ;;
        clean)
            clean_project
            ;;
        deploy)
            deploy_project
            ;;
        run)
            run_application "$@"
            ;;
        test)
            run_tests
            ;;
        package)
            package_release
            ;;
        env)
            configure_environment "$@"
            ;;
        env-clean)
            clean_environment
            ;;
        fetch-deps)
            fetch_third_party_libs
            ;;
        clean-deps)
            clean_third_party_libs
            ;;
        fetch-mqtt)
            fetch_mqtt_sdk
            ;;
        clean-mqtt)
            clean_mqtt_sdk
            ;;
        create)
            create_project "$@"
            ;;
        list)
            list_projects
            ;;
        build-project)
            build_specific_project "$@"
            ;;
        run-project)
            run_specific_project "$@"
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_error "未知命令: $command"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"